package com.ash.other;

import com.ash.util.ConnectionUtil;

import java.sql.*;
import java.util.Objects;
import java.util.Scanner;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/6 16:09
 * @Author : Chen Chao
 * @File : connection.com.ash.other.Test01.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 */
public class Test01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String name = scanner.nextLine();
        System.out.println("请输入密码");
        int password = scanner.nextInt();
        login01(name,password);
        login02(name,password);
    }

    /**
     * 普通登录
     * @param name 用户名
     * @param password 密码
     */
    private static void login02(String name, int password) {
        Connection connection=null;
        Statement statement=null;
        try {
            connection= ConnectionUtil.getConnection();
            statement = Objects.requireNonNull(connection).createStatement();
            String sql="select * from user where name='"+name+"'and password="+password;
            System.out.println(sql);
            ResultSet resultSet = statement.executeQuery(sql);
            if(resultSet.next()){
                System.out.println("欢迎回来，"+name+"学渣");
            }
            else {
                System.out.println("密码不对哦！");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionUtil.close(connection,statement,null);
        }
    }

    /**
     * 预编译登录
     * @param name 用户名
     * @param password 密码
     */
    private static void login01(String name, int password) {
        Connection connection=null;
        PreparedStatement ps=null;
        try {
            connection= ConnectionUtil.getConnection();
            /*个人认为，预编译后只识别数据，不识别和编译sql,所以单引号会被转义，*/
            ps= Objects.requireNonNull(connection).
                    prepareStatement("select * from user where name=? and password=?");
            ps.setObject(1,name);
            ps.setObject(2,password);
            ResultSet resultSet = ps.executeQuery();
            if(resultSet.next()){
                System.out.println("欢迎回来，"+name+"学渣");
            }
            else {
                System.out.println("别注入了，不可能的");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionUtil.close(connection,ps,null);
        }
    }
}
